﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using util;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace 文件管理
{
    public partial class 设备文件管理 : Form
    {
        UdpListener udpListener;
        UdpManager udp;
        private SynchronizationContext _syncContext;
        SocketClient socketClient = new SocketClient();

        string selectIp;

        string path;

        FileBean selectFile;

        public 设备文件管理()
        {
            _syncContext = SynchronizationContext.Current;
            InitializeComponent();
            socketClient.setListener(new SL(this));
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if(!socketClient.isRunning)
            {
                MessageBox.Show("请先连接！");
                return;
            }
            openFileDialog1.ShowDialog(this);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            ImageList imageList = new ImageList();
            try
            {
                imageList.Images.Add(System.Drawing.Image.FromFile("directory.png"));
                imageList.Images.Add(System.Drawing.Image.FromFile("file.png"));
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("文件未找到：" + ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show("无权访问文件：" + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message);
            }

            //imageList.Images.Add(Image.FromFile("d://anlogo.png"));
            // ... 添加更多图标

            // 设置 ListView 的 LargeImageList 属性
            listView1.LargeImageList = imageList;
            listView1.SmallImageList = imageList;
            listView1.View = View.LargeIcon;

            udp = new UdpManager();
            udpListener = new UL(this);
            udp.setListener(udpListener);
            udp.StartListening();

        }

        private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            Console.WriteLine("listView1_SelectedIndexChanged_1");
            if (listView1.SelectedItems.Count > 0)
            {
                // 获取第一个选中的项
                ListViewItem selectedItem = listView1.SelectedItems[0];

                // 在这里处理选中的项
                Console.WriteLine("Selected Item: " + selectedItem.Text);

                FileBean file = selectedItem.Tag as FileBean;
                selectFile = file;

            }
        }

        private void listView1_MouseClick(object sender, MouseEventArgs e)
        {
            Console.WriteLine("listView1_MouseClick");
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            Console.WriteLine("listView1_DoubleClick");
            if (listView1.SelectedItems.Count > 0)
            {
                // 获取第一个选中的项（在单选模式下，这将是唯一选中的项）
                ListViewItem selectedItem = listView1.SelectedItems[0];

                // 获取该项的文本
                string selectedText = selectedItem.Text;

                FileBean file = selectedItem.Tag as FileBean;
                if (file.isFile)
                {
                    socketClient.reqFile(file.path);
                }
                else
                {
                    socketClient.reqFileList(file.path);
                }
                
            }
            else
            {
                // 如果没有选中的项，可以显示一个消息或者什么也不做
                //MessageBox.Show("No item is selected.");
            }

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        void NotifyDevicesDataChange(List<Device> devices)
        {
            Console.WriteLine($"NotifyDevicesDataChange size = {devices.Count}");

            _syncContext.Post(state =>
            {
                listView2.Items.Clear();
                List<Device> devicesList = (List<Device>)state;
                foreach (Device device in devicesList)
                {
                    ListViewItem item = new ListViewItem(device.ip + "-" + device.name);
                    listView2.Items.Add(item);
                }
            }, devices);
        }


        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 检查是否有项被选中
            if (listView2.SelectedItems.Count > 0)
            {
                // 获取第一个选中的项
                ListViewItem selectedItem = listView2.SelectedItems[0];

                // 获取项的文本（适用于非Details视图或Details视图中的第一列）
                string itemText = selectedItem.Text;
                selectIp = itemText.Split('-')[0];
            }
            else
            {
                // 如果没有项被选中，可以执行一些其他操作或不做任何操作
                //MessageBox.Show("没有选中任何项。");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (socketClient.isRunning)
            {
                socketClient.Stop();
                button2.Text = "连接";
                label1.Text = "当前无连接";
            }
            else if (selectIp != null)
            {
                bool connect = socketClient.connect(selectIp);
                label1.Text = connect?"连接成功：" + selectIp:"连接失败";
                if (connect)
                {
                    button2.Text = "断开";
                    socketClient.send("电脑连接");
                    socketClient.reqFileList("/sdcard/");
                }
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            Console.WriteLine(openFileDialog1.FileName);
            socketClient.sendFile(openFileDialog1.FileName);
        }

        void ShowFileList(DirectoryBean b)
        {
            Console.WriteLine("ShowFileList:" + b.path);
            List<FileBean> list = b.children;
            path = b.path;
            _syncContext.Post(state =>
            {
                listView1.Items.Clear();
                List<FileBean> devicesList = (List<FileBean>)state;
                foreach (FileBean file in list)
                {
                    string fileName = Path.GetFileName(file.path);
                    ListViewItem item1 = new ListViewItem(fileName);
                    item1.ImageIndex = file.isFile?1:0; // 假设你要使用imageList1中的第一个图标
                    item1.Tag = file;
                    listView1.Items.Add(item1);
                }
            }, list);


        }

        void showSocketClose()
        {

            _syncContext.Post(state =>
            {
                label1.Text = "连接断开";
                button2.Text = "连接";
            }, "");

        }

        void showDownloadPercent(int percent)
        {

            _syncContext.Post(state =>
            {
                label2.Text = "进度：" + percent;
            }, percent);

        }

        void showMsg(string msg)
        {

            _syncContext.Post(state =>
            {
                label2.Text = msg;
            }, msg);

        }

        class UL : UpdListenerImpl
        {
            设备文件管理 form1;
            public UL(设备文件管理 f)
            {
                form1 = f;
            }
            protected override void notifyDataChange(List<Device> data)
            {
                Console.WriteLine($"{data.Count} devices");
                form1.NotifyDevicesDataChange(data);
            }
        }

        class SL : SocketListener
        {

            设备文件管理 form1;
            public SL(设备文件管理 f)
            {
                form1 = f;
            }

            public void OnFileList(DirectoryBean b)
            {
                form1.ShowFileList(b);
            }

            public void onSocketClose()
            {
                form1.showSocketClose();
            }

            public void OnPercent(int percent)
            {
               // Console.WriteLine($"{percent:0.##}%");
                form1.showDownloadPercent(percent);
            }

            public void OnDownloadResult(bool success, string msg)
            {
                form1.showMsg(msg);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!socketClient.isRunning)
            {
                MessageBox.Show("请先连接！");
                return;
            }
            if (path == null)
            {
                return;
            }
            if(path.Equals("/sdcard/") || path.Equals("/sdcard"))
            {

            }
            else
            {
                string directoryPath = Path.GetDirectoryName(path);
                directoryPath = directoryPath.Replace("\\", "/");
                Console.WriteLine("The parent directory is: " + directoryPath);
                socketClient.reqFileList(directoryPath);
            }
        }

        private void dragFile(object sender, DragEventArgs e)
        {
            // 获取拖动的文件路径
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                socketClient.sendFilesToPath(files);
            }
        }

        private void dragEnter(object sender, DragEventArgs e)
        {
            // 判断拖动的数据是否是文件
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if(selectFile != null)
            {
                socketClient.deleteFile(selectFile.path);
            }
        }
    }
}
